package com.example.hudongwx.myclass0719application.fragment;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hudongwx.myclass0719application.API;
import com.example.hudongwx.myclass0719application.Json.MyJsonObj;
import com.example.hudongwx.myclass0719application.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 聚赞的窗口
 * Created by hudongwx on 16-10-26.
 */
@ContentView(R.layout.fragjuzan)
public class FragJuZan extends Fragment {
    @ViewInject(R.id.frajuzan_textview_fenlei)
    private TextView textViewf;
    @ViewInject(R.id.frajuzan_textview_shaixuan)
    private TextView textViews;
    @ViewInject(R.id.frajuzan_textview_paixu)
    private TextView textViewp;
    //receyecellview
    @ViewInject(R.id.fragjuzan_recyclerview)
    private RecyclerView recyclerView;
    //中间的那个显示图片的按钮
    @ViewInject(R.id.fragjuzan_iv)
    private ImageView imageView;

    //review外面的包裹framalayout

    @ViewInject(R.id.fragjuzan_gone_iv)
    private ImageView imageViewgone;


    @ViewInject(R.id.frajuzan_recyc_framelayout)
    private FrameLayout flcon;
    //没有数据要显示的图片
    @ViewInject(R.id.fragment3_gone_1)
    private RelativeLayout rlcon;


    private MyAdaper adapter;//适配器
    private int nowPage = 1;//需要显示的页码
    private String typeV = "null";//分类
    private String brandV = "0";//筛选
    private String sortV = "0";//排序

    private GridLayoutManager gridLayoutManager;

    //分类的弹出popwin
    private PopupWindow popupWindowType;
    private LinearLayout popViewType;
    //筛选的弹出popwin
    private PopupWindow popupWindowBrand;
    private LinearLayout popViewBrand;
    //排序的弹出popwin
    private PopupWindow popupWindowSort;
    private LinearLayout popViewSort;


    private String[] types = new String[]{null, "2", "3", "5", "4", "8"};

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //初始化
        View  view=x.view().inject(this, inflater, container);
        init();
        return view;
    }

    /**
     * 处理分类的方法
     *
     * @param view
     */
    @Event(R.id.frajuzan_textview_fenlei)
    private void fenLei(final View view) {
        if (view.isSelected()) {
            view.setSelected(false);
            if (null!=popupWindowType) {
                popupWindowType.dismiss();
            }
        } else {
            view.setSelected(true);
            if (popViewType == null) {
                //先解析布局
                popViewType = (LinearLayout) getActivity().getLayoutInflater().inflate(R.layout.fragjuzan_type_top, null);

                popupWindowType = new PopupWindow(popViewType, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                //设置点击事件
                View.OnClickListener onClickListener = new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        view.setSelected(false);
                        popupWindowType.dismiss();
                        typeV = types[Integer.parseInt(v.getTag() + "")];
                        nowPage = 1;
                        //选谁显示谁
                        ((TextView) view).setText(((TextView) v).getText());
                        //重新设置被选中的那个item
                        setDrowItem(popViewType, (TextView) v);
                        //加载数据之前，先清空原来的数据
                        adapter.clear();
                        //重新加载数据
                        loadData();
                    }
                };
                //依次给按钮添加点击事件
                int len = popViewType.getChildCount();
                for (int i = 0; i < len; i++) {
                    View childAt = popViewType.getChildAt(i);
                    childAt.setOnClickListener(onClickListener);
                    childAt.setTag(i + "");
                    //设置默认选中的item
                    if(0==i){
                        childAt.setSelected(true);
                    }
                }
                //点击其他部分关闭选择
                popViewType.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindowType.dismiss();
                        view.setSelected(false);
                    }
                });

            }
            //显示数据
            popupWindowType.showAsDropDown(view);
        }


    }

    /**
     * 初始化下拉菜单控件的方法
     *
     * @param linearLayout
     * @param view
     */
    private void setDrowItem(LinearLayout linearLayout, TextView view) {
        //给按钮添加点击事件
        int len = linearLayout.getChildCount();
        for (int i = 0; i < len; i++) {
            TextView chilen = (TextView) linearLayout.getChildAt(i);
            chilen.setSelected(false);
            chilen.setPadding(50, 10, 0, 10);
            //去掉那个选中的小图片
            chilen.setCompoundDrawables(null, null, null, null);
        }
        view.setPadding(25, 10, 0, 10);

        Drawable drawable = getResources().getDrawable(R.drawable.collection_pick);
        /// 这一步必须要做,否则不会显示.
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        view.setCompoundDrawables(drawable, null, null, null);
        view.setSelected(true);

    }

    /**
     * 初始化界面
     */
    private void init() {
             adapter=new MyAdaper();
        gridLayoutManager=new GridLayoutManager(getActivity(),4);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(adapter);
        loadData();
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState==RecyclerView.SCROLL_STATE_IDLE&&gridLayoutManager.findLastCompletelyVisibleItemPosition()+1==adapter.getItemCount())
                loadData();
            }
        });

    }

    //recycler的适配器
    class MyAdaper extends RecyclerView.Adapter<MyViewHolder> {
        private List<Item> data = new ArrayList<>();//用来放列表的数据

        public MyAdaper() {
        }

        public MyAdaper(List<Item> data) {
            this.data.addAll(data);
            notifyDataSetChanged();
        }

        //清空原来的数据
        public void clear() {
            data.clear();
            notifyDataSetChanged();
        }

        /**
         * 加载新的一页的时候，加载数据
         *
         * @param tempData
         */
        public void addMore(List<Item> tempData) {
            this.data.addAll(tempData);

            //从哪开始，，，加载的新的数据数量
            notifyItemRangeChanged(this.data.size() - tempData.size(), tempData.size());
        }


        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragmentjuzan_like, null);


            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            //绑定显示图片
            Item item = data.get(position);
            x.image().bind(holder.imageview, item.getBrandIcon());
            if ("1".equals(item.isDown)) {
                //正在降价
                //绘制左边降价的图片
                Drawable drawable = getResources().getDrawable(R.drawable.down);
                /// 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                holder.textview.setCompoundDrawables(drawable, null, null, null);
                holder.textview.setBackgroundResource(0);
                holder.textview.setText("闪降中");
                holder.textview.setTextColor(Color.RED);
            } else if (item.getMax() <= item.getLikeNum()) {
                //集满了
                Drawable drawable = getResources().getDrawable(R.drawable.collection_full);
                /// 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                holder.textview.setCompoundDrawables(drawable, null, null, null);
                holder.textview.setText("满赞");
                holder.textview.setTextColor(Color.RED);
                holder.textview.setBackgroundResource(0);
            } else {
                //还在积攒
                Drawable drawable = getResources().getDrawable(R.drawable.collection_press);
                /// 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                holder.textview.setCompoundDrawables(drawable, null, null, null);
                holder.textview.setText("点赞");
                holder.textview.setBackgroundResource(R.drawable.registerbutton);
                holder.textview.setTextColor(Color.BLACK);
            }
        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }

    //recycler中，一个布局的item
    class MyViewHolder extends RecyclerView.ViewHolder {
        private ImageView imageview;
        private TextView textview;

        public MyViewHolder(View itemView) {
            super(itemView);
            imageview = (ImageView) itemView.findViewById(R.id.fragment3_like_item_img);
            textview = (TextView) itemView.findViewById(R.id.fragment3_like_item_iv);
        }
    }

    /**
     * 把获取到的json数据，解析添加到一个List里面
     *
     * @param data
     * @return
     */
    private List<Item> parser2ListItem(JSONObject data) {
        List<Item> list = new ArrayList<>();
        try {
            JSONArray jsonArray = data.getJSONArray("brands");
            int len = jsonArray.length();
            for (int i = 0; i < len; i++) {
                list.add(new Item(jsonArray.getJSONObject(i)));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 加载数据，多次调用，可以加载更多
     */
    private void loadData() {
        //发送请求去加载数据
        RequestParams requestParams = new RequestParams(API.getLike(nowPage, typeV, brandV, sortV));
        x.http().get(requestParams, new Callback.CommonCallback<MyJsonObj>() {
            @Override
            public void onSuccess(MyJsonObj result) {

                List<Item> items = parser2ListItem(result);
                if (items.size() == 0 && nowPage == 1) {
                 // 如果是第一眼没有数据
                    flcon.setVisibility(View.GONE);

                   rlcon.setVisibility(View.VISIBLE);
                    return;
                } else if (items.size() == 0 && nowPage != 1) {
                    //如果是后面的没有数据
                    Toast.makeText(getActivity(), "没有更多了", Toast.LENGTH_SHORT).show();
                    return;
                }
                //恢复显示内容，隐藏没有内容的提示
                flcon.setVisibility(View.VISIBLE);
                rlcon.setVisibility(View.GONE);

                adapter.addMore(items);
                if (nowPage == 1) {
                    //如果是第一也，就加载头部图片
                    try {
                        x.image().bind(imageView, result.getString("title"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                nowPage++;//当前页码加载成功，把页码+1

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }


    /**
     * 一个条目的数据
     */
    class Item {
        private int brandId;
        private int isLike;
        private String brandName;
        private String brandIcon;
        private int likeNum;
        private int max;
        private String isDown;

        public Item(JSONObject item) throws JSONException {
            brandId = item.getInt("brandId");
            isLike = item.getInt("isLike");
            brandName = item.getString("brandName");
            brandIcon = item.getString("brandIcon");
            likeNum = Integer.parseInt(item.getString("likeNum"));
            max = Integer.parseInt(item.getString("max"));
            isDown = item.getString("isDown");
        }

        public String getBrandIcon() {
            return brandIcon;
        }

        public void setBrandIcon(String brandIcon) {
            this.brandIcon = brandIcon;
        }

        public int getBrandId() {
            return brandId;
        }

        public void setBrandId(int brandId) {
            this.brandId = brandId;
        }

        public String getBrandName() {
            return brandName;
        }

        public void setBrandName(String brandName) {
            this.brandName = brandName;
        }

        public String getIsDown() {
            return isDown;
        }

        public void setIsDown(String isDown) {
            this.isDown = isDown;
        }

        public int getIsLike() {
            return isLike;
        }

        public void setIsLike(int isLike) {
            this.isLike = isLike;
        }

        public Integer getLikeNum() {
            return likeNum;
        }

        public void setLikeNum(Integer likeNum) {
            this.likeNum = likeNum;
        }

        public Integer getMax() {
            return max;
        }

        public void setMax(Integer max) {
            this.max = max;
        }
    }

}
